<?php

/**
 * Action Helper for loading forms
 * 
 * @uses Zend_Controller_Action_Helper_Abstract
 */
class Helper_FormLoader extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * @var Zend_Loader_PluginLoader
     */
    public $pluginLoader;

    /**
     * Constructor: initialize plugin loader
     * 
     * @return void
     */
    public function __construct()
    {
        $this->pluginLoader = new Zend_Loader_PluginLoader();
    }

    /**
     * Loads a form form the given module or current module with the provided
     * options
     * 
     * @param  string $name 
     * @param  string $module
     * @param  array|Zend_Config $options 
     * @return Zend_Form
     */
    public function load($name, $module = null, $options = null)
    {
        if ($module === null) {
            $module = $this->getRequest()->getModuleName();
        }

        $front   = $this->getFrontController();
        $default = $front->getDispatcher()
                         ->getDefaultModule();

        if (empty($module)) {
            $module = $default;
        }

        $moduleDirectory = $front->getControllerDirectory($module);
        $formsDirectory  = dirname($moduleDirectory) . '/forms';

        $prefix = (('default' == $module) ? '' : ucfirst($module) . '_')
                . 'Form_';
        $this->pluginLoader->addPrefixPath($prefix, $formsDirectory);

        $name      = ucfirst((string) $name);
        $formClass = $this->pluginLoader->load($name);
        return new $formClass($options);
    }

    /**
     * Strategy pattern: call helper as broker method
     * For example:
     * $this->_helper->formLoader->load('login', 'default');
     *
     * @param  string $name 
     * @param  string $module
     * @param  array|Zend_Config $options 
     * @return Zend_Form
     */
    public function direct($name, $module = null, $options = null)
    {
        return $this->load($name, $module, $options);
    }
}
